/**
 * MetadataTableModelListener.java
 * 2012-2-21 下午10:31:12
 */
package xgenerator.ui.swing.adapter;

import java.awt.Component;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import xgenerator.ui.swing.MetadataTable;
import xgenerator.ui.swing.model.MetadataTableModel;

/**
 * <p>
 * Title:类的中文名
 * </p>
 * <p>
 * Description:具体功能见各方法描述
 * </p>
 * <p>
 * Copyright:Copyright (c) 2012
 * </p>
 * 
 * @author <a href="mailto:lishushan@gmail.com">liss</a>
 * @version 1.0
 */
public class MetadataTableModelListener implements TableModelListener {
	
	/**
	 * UI组件
	 */
	private Component ui;
	
	/**
	 * constructor
	 * @param ui
	 */
	public MetadataTableModelListener(Component ui) {
		this.ui = ui;
	}

	/**
	 * <p>
	 * Title：tableModel改变事件处理
	 * </p>
	 * @param e
	 * @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent)
	 */
	public void tableChanged(TableModelEvent e) {
		if (e.getType() == TableModelEvent.UPDATE) {
			int selectedRow = e.getFirstRow();  //返回首个选定行的索引，如果没有选定的行，则返回 -1
			int selectedColumn = e.getColumn();  ////返回所有选定列的索引
			
			if(-1 != selectedRow && -1 != selectedColumn) {
				MetadataTable metadataTable = (MetadataTable) ui;
				
				if(MetadataTableModel.IS_KEY_FIELD_INDEX == selectedColumn) {//isKey
					Object cellValueObj = metadataTable.getValueAt(selectedRow, selectedColumn);
					boolean isKey = ((Boolean) cellValueObj).booleanValue();
					MetadataTableModel metadataTableModel = (MetadataTableModel) metadataTable.getModel();
					metadataTableModel.setCellEditableAt(isKey, selectedRow, MetadataTableModel.CONSTRAINT_TYPE_INDEX);
					metadataTableModel.setCellEditableAt(isKey, selectedRow, MetadataTableModel.REFERENCING_TABLE_INDEX);
					metadataTableModel.setCellEditableAt(isKey, selectedRow, MetadataTableModel.REFERENCING_COLUMN_INDEX);
					metadataTableModel.setCellEditableAt(isKey, selectedRow, MetadataTableModel.DELETE_RULE_INDEX);
					metadataTableModel.setValueAt(null, selectedRow, MetadataTableModel.CONSTRAINT_TYPE_INDEX);
					metadataTableModel.setValueAt(null, selectedRow, MetadataTableModel.REFERENCING_TABLE_INDEX);
					metadataTableModel.setValueAt(null, selectedRow, MetadataTableModel.REFERENCING_COLUMN_INDEX);
					metadataTableModel.setValueAt(null, selectedRow, MetadataTableModel.DELETE_RULE_INDEX);
				} else if(MetadataTableModel.IS_QUERY_FIELD_INDEX == selectedColumn) {//isQueryField
					Object cellValueObj = metadataTable.getValueAt(selectedRow, selectedColumn);
					boolean isQueryField = ((Boolean) cellValueObj).booleanValue();
					MetadataTableModel metadataTableModel = (MetadataTableModel) metadataTable.getModel();
					metadataTableModel.setCellEditableAt(isQueryField, selectedRow, MetadataTableModel.QUERY_MODE_INDEX);
					metadataTableModel.setValueAt(null, selectedRow, MetadataTableModel.QUERY_MODE_INDEX);
				}
			}
		}
	}

}
